<template>
  <div class="article-publish">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEditMode ? '编辑文章' : '发布文章' }}</span>
          <div class="header-actions">
            <el-button @click="saveDraft">保存草稿</el-button>
            <el-button type="primary" @click="publishArticle">
              {{ isEditMode ? '更新文章' : '发布文章' }}
            </el-button>
          </div>
        </div>
      </template>
      
      <el-form :model="articleForm" :rules="rules" ref="articleFormRef" label-width="120px">
        <!-- 文章标题 -->
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="articleForm.title"
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
            size="large"
          />
        </el-form-item>

        <!-- 富文本编辑器 -->
        <el-form-item label="文章内容" prop="content">
          <div class="editor-container">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden;"
              v-model="valueHtml"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>

        <!-- 文章封面 -->
        <el-form-item label="文章封面" prop="coverImage">
          <div class="cover-upload">
            <el-upload
              class="cover-uploader"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :http-request="customUpload"
            >
              <img v-if="articleForm.coverImage" :src="articleForm.coverImage" class="cover-image" />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tips">
              <p>建议尺寸：750 x 422 像素</p>
              <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
            </div>
          </div>
        </el-form-item>

        <!-- 发布时间 -->
        <el-form-item label="发布时间" prop="publishTime">
          <div class="publish-time-container">
            <el-date-picker
              v-model="articleForm.publishTime"
              type="datetime"
              placeholder="选择发布时间（不选择则立即发布）"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              :clearable="true"
              class="custom-datepicker"
            />
            
            <!-- 快捷时间选择按钮 -->
            <div class="quick-time-buttons">
              <el-button 
                size="small" 
                @click="setQuickTime(1)"
                :type="isQuickTimeSelected(1) ? 'primary' : 'default'"
              >
                1小时后
              </el-button>
              <el-button 
                size="small" 
                @click="setQuickTime(4)"
                :type="isQuickTimeSelected(4) ? 'primary' : 'default'"
              >
                4小时后
              </el-button>
              <el-button 
                size="small" 
                @click="setQuickTime(10)"
                :type="isQuickTimeSelected(10) ? 'primary' : 'default'"
              >
                10小时后
              </el-button>
              <el-button 
                size="small" 
                @click="clearPublishTime"
                :type="!articleForm.publishTime ? 'primary' : 'info'"
              >
                立即发布
              </el-button>
            </div>
          </div>
          
          <div class="publish-time-tips">
            <p>不选择时间将立即发布文章</p>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { uploadArticleFile, submitArticle, getArticleDetail } from '@/api/article'
import { useRoute } from 'vue-router'

// 路由
const route = useRoute()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = 'default' // 或 'simple'
const valueHtml = ref('<p>请在此输入文章内容...</p>')

// 表单引用
const articleFormRef = ref()

// 编辑模式相关
const isEditMode = ref(false)
const articleId = ref('')

// 表单数据
const articleForm = reactive({
  title: '',
  content: '',        // 纯文本内容
  contentHtml: '',    // 富文本内容
  coverImage: '',
  publishTime: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 工具栏配置 - 使用精确的工具栏配置，只包含需要的按钮
const toolbarConfig = {
  toolbarKeys: [
    'headerSelect',
    '|',
    'bold',
    'italic', 
    'underline',
    'through',
    'code',
    'sup',
    'sub',
    'clearStyle',
    '|',
    'color',
    'bgColor', 
    '|',
    'fontSize',
    'fontFamily',
    'lineHeight',
    '|',
    'bulletedList',
    'numberedList',
    'todo',
    '|',
    'emotion',
    'insertLink',
    'uploadImage',  // 明确包含图片上传
    'insertTable',
    'codeBlock',
    'divider',
    '|', 
    'undo',
    'redo',
    '|',
    'fullScreen'
    // 不包含任何视频相关按钮
  ]
}

// 编辑器配置
const editorConfig = {
  placeholder: '请输入文章内容...',
  MENU_CONF: {
    // 上传图片配置
    uploadImage: {
      // 自定义上传
      async customUpload(file, insertFn) {
        try {
          // 创建 FormData
          const formData = new FormData()
          formData.append('file', file)
          
          // 调用上传接口
          const response = await uploadArticleFile(formData)
          console.log('编辑器图片上传响应:', response)
          
          if (response && response.url) {
            // 上传成功，插入图片到编辑器
            insertFn(response.url, response.name || file.name, response.url)
          } else {
            ElMessage.error('图片上传失败')
          }
        } catch (error) {
          console.error('图片上传错误:', error)
          ElMessage.error('图片上传失败，请重试')
        }
      }
    }
  }
}

// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 从富文本内容中提取纯文本
const extractPlainText = (html) => {
  if (!html) return ''
  
  // 创建一个临时的DOM元素来解析HTML
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = html
  
  // 获取纯文本内容
  const plainText = tempDiv.textContent || tempDiv.innerText || ''
  
  // 清理多余的空白字符
  return plainText.replace(/\s+/g, ' ').trim()
}

// 初始化页面
const initializePage = async () => {
  // 检查是否为编辑模式
  const id = route.query.id
  if (id) {
    isEditMode.value = true
    articleId.value = id
    await loadArticleData(id)
  }
}

// 加载文章数据
const loadArticleData = async (id) => {
  try {
    const response = await getArticleDetail(id)
    console.log('编辑文章详情响应:', response)
    
    if (response) {
      // 只使用后端实际返回的字段
      articleForm.title = response.title || ''
      articleForm.coverImage = response.articleCover || ''
      
      // 处理发布时间 - 后端返回LocalDateTime格式
      if (response.publishTime) {
        // 如果后端返回的是字符串格式的时间，直接使用
        articleForm.publishTime = response.publishTime
      } else {
        articleForm.publishTime = ''
      }
      
      // 设置编辑器内容 - 优先使用富文本内容，如果没有则使用纯文本内容
      valueHtml.value = response.contentHtml || response.content || '<p>请在此输入文章内容...</p>'
      
      ElMessage.success('文章数据加载成功')
    }
  } catch (error) {
    console.error('加载文章数据失败:', error)
    ElMessage.error('加载文章数据失败，请重试')
  }
}

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用昨天及以前的日期
}


// 快捷时间设置
const setQuickTime = (hours) => {
  const now = new Date()
  const futureTime = new Date(now.getTime() + hours * 60 * 60 * 1000)
  const formattedTime = formatDate(futureTime)
  
  console.log('当前时间:', now)
  console.log('设置快捷时间:', hours, '小时后')
  console.log('计算后的时间:', futureTime)
  console.log('格式化后:', formattedTime)
  
  articleForm.publishTime = formattedTime
  console.log('设置完成，当前值:', articleForm.publishTime)
}

// 检查当前选择的时间是否匹配快捷时间
const isQuickTimeSelected = (hours) => {
  if (!articleForm.publishTime) return false
  
  // 计算目标时间字符串
  const now = new Date()
  const targetTime = new Date(now.getTime() + hours * 60 * 60 * 1000)
  const targetTimeString = formatDate(targetTime)
  
  // 比较字符串（允许1分钟误差，比较到分钟级别）
  const selectedMinute = articleForm.publishTime.substring(0, 16) // YYYY-MM-DD HH:mm
  const targetMinute = targetTimeString.substring(0, 16)
  
  return selectedMinute === targetMinute
}

// 清除发布时间
const clearPublishTime = () => {
  articleForm.publishTime = ''
  console.log('清除发布时间')
}

// 封面上传前验证
const beforeCoverUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('封面只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('封面大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传方法
const customUpload = async (option) => {
  try {
    // 创建 FormData
    const formData = new FormData()
    formData.append('file', option.file)
    
    // 调用上传接口
    const response = await uploadArticleFile(formData)
    console.log('自定义上传响应:', response)
    
    if (response && response.url) {
      // 直接设置封面图片
      articleForm.coverImage = response.url
      ElMessage.success('封面上传成功')
      // 上传成功
      option.onSuccess(response)
    } else {
      option.onError(new Error('上传失败'))
    }
  } catch (error) {
    console.error('封面上传错误:', error)
    option.onError(error)
    ElMessage.error('封面上传失败，请重试')
  }
}

// 保存草稿
const saveDraft = async () => {
  // 更新文章内容
  articleForm.contentHtml = valueHtml.value           // 富文本内容
  articleForm.content = extractPlainText(valueHtml.value)  // 纯文本内容
  
  try {
    await articleFormRef.value.validate()
    // 这里调用保存草稿的API
    console.log('保存草稿:', articleForm)
    ElMessage.success('草稿保存成功')
  } catch (error) {
    ElMessage.error('请完善文章信息')
  }
}

// 发布/更新文章
const publishArticle = async () => {
  // 更新文章内容
  articleForm.contentHtml = valueHtml.value           // 富文本内容
  articleForm.content = extractPlainText(valueHtml.value)  // 纯文本内容
  
  try {
    await articleFormRef.value.validate()
    
    const actionText = isEditMode.value ? '更新' : '发布'
    const confirmMessage = articleForm.publishTime 
      ? `确认在 ${articleForm.publishTime} ${actionText}这篇文章吗？`
      : `确认立即${actionText}这篇文章吗？`
    
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: `确认${actionText}`,
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 准备请求数据
    const requestData = {
      title: articleForm.title,
      content: articleForm.content,        // 纯文本内容
      contentHtml: articleForm.contentHtml, // 富文本内容
      articleCover: articleForm.coverImage || null
    }
    
    // 编辑模式需要传入文章ID
    if (isEditMode.value) {
      requestData.id = articleId.value
    }
    
    // 如果有选择发布时间，则添加到请求数据中
    if (articleForm.publishTime) {
      requestData.publishTime = articleForm.publishTime
    }
    
    // 调用提交文章的API
    await submitArticle(requestData)
    ElMessage.success(`文章${actionText}成功`)
    
    // 如果是新增模式，发布成功后清空表单
    if (!isEditMode.value) {
      resetForm()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(`${isEditMode.value ? '更新' : '发布'}文章失败:`, error)
      ElMessage.error(`${isEditMode.value ? '更新' : '发布'}失败，请重试`)
    }
  }
}

// 重置表单
const resetForm = () => {
  articleForm.title = ''
  articleForm.content = ''
  articleForm.contentHtml = ''
  articleForm.coverImage = ''
  articleForm.publishTime = ''
  valueHtml.value = '<p>请在此输入文章内容...</p>'
  articleFormRef.value.resetFields()
}

// 时间选择器相关方法
const formatPreview = (date) => {
  if (!date) return ''
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const formatDate = (date) => {
  if (!date) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}


// 调试：打印当前时间格式
const debugTimeFormat = () => {
  if (articleForm.publishTime) {
    console.log('当前选择的时间:', articleForm.publishTime)
    console.log('格式化后的时间:', formatDate(articleForm.publishTime))
  } else {
    console.log('未选择时间')
  }
}

// 组件挂载时初始化
onMounted(() => {
  initializePage()
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>

<style scoped lang="scss">
.article-publish {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
    
    .header-actions {
      .el-button {
        margin-left: 10px;
      }
    }
  }
  
  .editor-container {
    border: 1px solid #ccc;
    z-index: 100;
  }
  
  .cover-upload {
    display: flex;
    align-items: flex-start;
    gap: 20px;
    
    .cover-uploader {
      .cover-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 200px;
        height: 120px;
        line-height: 120px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: all 0.3s;
        
        &:hover {
          border-color: #409EFF;
          color: #409EFF;
        }
      }
      
      .cover-image {
        width: 200px;
        height: 120px;
        object-fit: cover;
        border-radius: 6px;
        cursor: pointer;
      }
    }
    
    .upload-tips {
      flex: 1;
      
      p {
        margin: 0 0 8px 0;
        color: #909399;
        font-size: 14px;
      }
    }
  }
  
  .publish-time-container {
    width: 100%;
    
    .custom-datepicker {
      width: 100%;
      max-width: 400px;
    }
    
    .quick-time-buttons {
      margin-top: 12px;
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      
      .el-button {
        margin: 0;
      }
    }
  }
}
  
  .publish-time-tips {
    margin-top: 8px;
    
    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

:deep(.w-e-text-placeholder) {
  color: #c0c4cc;
}

/* 日期时间选择器样式修复 */
:deep(.el-date-editor) {
  width: 100%;
  max-width: 400px;
}

:deep(.el-date-editor.el-input__wrapper) {
  width: 100%;
}

/* 确保弹窗内时间选择部分正常显示 */
:deep(.el-picker-panel__body) {
  display: flex;
  flex-direction: column;
  min-height: auto;
}

:deep(.el-picker-panel__content) {
  overflow: visible;
}

:deep(.el-time-panel) {
  position: relative;
  width: auto;
  margin: 0;
  border: none;
}

</style>
